package com.dreamoo.service.factory;

import com.dreamoo.common.enums.LoginType;
import com.dreamoo.service.strategy.login.UserLoginStrategy;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 山顶洞人郑某
 * @className UserLoginFactory.java 创建用户登录工厂类
 * @date 2025 05 08
 */
@Component
public class UserLoginFactory implements ApplicationContextAware {
    /**
     * 用户登录的策略集合
     */
    private Map<LoginType, UserLoginStrategy> userLoginStrategyMap;

    private  ApplicationContext applicationContext;

    @PostConstruct
    public void init() {
        //从Spring上下文中获取到所有用户登录的策略
        Map<String, UserLoginStrategy> strategyMap = applicationContext.getBeansOfType(UserLoginStrategy.class);
        userLoginStrategyMap = new HashMap<>(8);
        // 遍历策略并按 LoginType 分类
        strategyMap.forEach((beanName, strategy) -> {
            LoginType loginType = strategy.loginType();
            // 检查是否已存在相同 LoginType，避免策略覆盖
            if (userLoginStrategyMap.putIfAbsent(loginType, strategy) != null) {
                throw new IllegalStateException(
                        "Duplicate LoginType: " + loginType +
                                " found in UserLoginStrategy [" + beanName + "]. Conflict with existing strategy.");
            }
        });
    }

    /**
     * 根据登录类型获取对应的用户登录策略实例。
     *
     * @param loginType 指定的登录类型枚举值，用于标识不同的登录验证方式
     * @return UserLoginStrategy 返回与登录类型匹配的策略实现对象，若未找到匹配项则返回null
     */
    public UserLoginStrategy getUserLoginStrategy(LoginType loginType) {
        return userLoginStrategyMap.get(loginType);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
